<template>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <!-- <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
                <el-select v-model="queryParams.unit" placeholder="请选择单位" clearable>
                    <el-option v-for="dict in unit_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" :disabled="!permession" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table height="75vh" :summary-method="getSummaries" show-summary
        :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" border v-loading="loading" :data="matchingList"
        @selection-change="handleSelectionChange">
        <el-table-column label="名称" align="center" prop="name">
            <template #default="scope">
                <el-select :disabled="!permession" @change="dataChange(scope.row)" clearable filterable
                    v-model="scope.row.name" placeholder="请选择">
                    <el-option v-for="dict in matching_type" :key="dict.value" :label="dict.label"
                        :value="dict.label"></el-option>
                </el-select>
            </template>
        </el-table-column>

        <el-table-column label="单位" align="center" prop="unit">
            <template #default="scope">
                <el-select :disabled="!permession" @change="dataChange(scope.row)" v-model="scope.row.unit"
                    placeholder="请选择单位" clearable>
                    <el-option v-for="dict in unit_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </template>
        </el-table-column>


        <el-table-column label="数量" prop="amount" align="center">
            <template #default="scope">
                <el-input :disabled="!permession" @blur="dataChange(scope.row)" type="number" @wheel.native.prevent
                    v-model="scope.row.amount" />
            </template>
        </el-table-column>

        <el-table-column label="单价" align="center">
            <template #default="scope">
                <el-input :disabled="!permession" @blur="dataChange(scope.row)" type="number" @wheel.native.prevent
                    v-model="scope.row.price" />
            </template>
        </el-table-column>


        <el-table-column label="总价" align="center" prop="totalPrice" />


        <el-table-column label="备注" align="center">
            <template #default="scope">
                <el-input :disabled="!permession" @blur="dataChange(scope.row)" @wheel.native.prevent
                    v-model="scope.row.remark" />
            </template>
        </el-table-column>

        <el-table-column label="操作人" align="center" prop="operator" />

        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column> -->
    </el-table>


    <!-- 添加或修改配套施工对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
        <el-form ref="matchingRef" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="20">
                    <el-form-item label="名称" prop="name">
                        <el-select clearable filterable v-model="form.name" placeholder="请选择">
                            <el-option v-for="dict in matching_type" :key="dict.value" :label="dict.label"
                                :value="dict.label"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>


                <el-col :span="7">
                    <el-form-item label="数量" prop="amount">
                        <el-input @blur="addChange()" type="number" @wheel.native.prevent v-model="form.amount"
                            placeholder="请输入数量" />
                    </el-form-item>
                </el-col>



                <el-form-item label="单价" prop="price">
                    <el-input @blur="addChange()" type="number" @wheel.native.prevent v-model="form.price"
                        placeholder="请输入单价" />
                </el-form-item>
                <el-form-item label="总价" prop="totalPrice">
                    <el-input disabled type="number" @wheel.native.prevent v-model="form.totalPrice"
                        placeholder="请输入总价" />
                </el-form-item>

                <el-col :span="7">
                    <el-form-item label="单位" prop="unit">
                        <el-select v-model="form.unit" placeholder="请选择单位">
                            <el-option v-for="dict in unit_type" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>


                <!-- <el-form-item label="负责人" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>

                <el-form-item label="施工内容" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->


            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="Matching">
import { listMatching, getMatching, delMatching, addMatching, updateMatching, getMatchingTotal } from "@/api/project/matching";

import { getPermission, } from "@/api/project/project";
import { ref } from "vue";


const { proxy } = getCurrentInstance();
const { unit_type } = proxy.useDict('unit_type');
const { matching_type } = proxy.useDict('matching_type');

const props = defineProps({
    datas: {
        type: Object, // 指定类型为对象
        required: true, // 是否必填
    },
});
const { datas } = toRefs(props);


function dataChange(row) {
    console.log("更新的数据", row);

    //计算总价
    row.totalPrice = parseFloat((row.amount * row.price).toFixed(2));

    updateMatching(row).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        getList();
    });
}

const projectNo = ref()


function addChange() {
    //计算总价
    form.value.projectNo = datas.value.projectNo
    form.value.totalPrice = parseFloat((form.value.amount * form.value.price).toFixed(2));

}


function getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = `合计（共 ${data.length} 条）`;
            return;
        }

        const prop = column.property;

        // 需要统计的列配置
        const statsColumns = {
            totalPrice: { name: '总价', format: 'money' },
            amount: { name: '数量', format: '' }
        };

        if (statsColumns[prop]) {
            const values = data.map(item => Number(item[prop]));
            if (!values.every(value => isNaN(value))) {
                const sum = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    return isNaN(value) ? prev : prev + value;
                }, 0);

                // 格式化输出
                switch (statsColumns[prop].format) {
                    case 'int':
                        sums[index] = Math.round(sum).toString(); // 四舍五入取整，转为字符串
                        break;
                    case 'money':
                        sums[index] = '￥ ' + sum.toFixed(2); // 四舍五入保留两位小数并添加货币符号
                        break;
                    default:
                        sums[index] = sum.toString();
                }
            } else {
                sums[index] = 'N/A';
            }
        } else {
            sums[index] = '';
        }
    });

    return sums;
}


const matchingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNo: null,
        matchingType: null,
        name: null,
        unit: null,
    },
    rules: {
        name: [
            { required: true, message: "名称不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询配套施工列表 */
function getList() {
    loading.value = true;
    queryParams.value.projectNo = datas.value.projectNo
    listMatching(queryParams.value).then(response => {
        matchingList.value = response;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        projectNo: null,
        matchingType: null,
        name: null,
        unit: null,
        amount: null,
        price: null,
        totalPrice: null,
        operator: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        loginIp: null,
        loginDate: null
    };
    proxy.resetForm("matchingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

const permession = ref(false)

//只有在项目立项  立项前期  实施 验收 核算 这几个环节允许编辑
const currentPhase = ref(false)

async function getPer() {


    let params = {
        projectNo: datas.value.projectNo,
        postIds: [2, 5, 7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }

    projectNo.value = datas.value.projectNo

    console.log("params", params);


    const res = await getPermission(params).then((response) => {
        console.log("权限111", response.data);

        console.log("项目信息", datas.value);

        if (Number(datas.value.phaseId) > 5) {
            console.log("???????????");

            permession.value = false
            return
        } else {
            permession.value = response.data
            return permession.value
        }


    });
}

onMounted(async () => {
    await getPer()
});


/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加配套施工";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    console.log("配套", row);

    reset();
    const _id = row.id || ids.value
    getMatching(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改配套施工";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["matchingRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateMatching(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                form.value.projectNo = projectNo.value
                addMatching(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除配套施工编号为"' + _ids + '"的数据项？').then(function () {
        return delMatching(_ids);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('project/matching/export', {
        ...queryParams.value
    }, `matching_${new Date().getTime()}.xlsx`)
}

getList();
</script>